package cs4280.ass2.action;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.collections.functors.EqualPredicate;
import org.apache.commons.lang.time.DateUtils;

import cs4280.ass2.entity.House;
import cs4280.ass2.entity.ScheduleTO;
import cs4280.ass2.persistence.HouseDao;
import cs4280.ass2.persistence.ScheduleDao;
import cs4280.ass2.util.httpUtils;

public class CinemaAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<House> houseList = HouseDao.getInstance().retrieveAllHouse();
		Map<Long, List<ScheduleTO>> houseScheduleMap = new HashMap<Long, List<ScheduleTO>>();

		for (House house : houseList) {
			List<ScheduleTO> scheduleList = ScheduleDao.getInstance()
					.retrieveScheduleTOByHouse(house.getId());
			if (!httpUtils.isLogined(req)) {
				scheduleList = (List<ScheduleTO>) CollectionUtils.select(
						scheduleList, new Predicate() {
							@Override
							public boolean evaluate(Object object) {
								ScheduleTO scheduleTO = (ScheduleTO) object;
								return DateUtils.isSameDay(new Date(),
										scheduleTO.getScheduleStart());
							}
						});
			}

			houseScheduleMap.put(house.getId(), scheduleList);
		}

		req.setAttribute("houseList", houseList);
		req.setAttribute("houseScheduleMap", houseScheduleMap);
		getServletContext().getRequestDispatcher("/cinema.jsp").forward(req,
				resp);
	}
}
